﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;

namespace Mrc.Config
{
    public class LocationConfigStore
    {
        public static IConfiguration configuration { get; set; }

        private static Dictionary<string, object> KeyValue { get; set; } = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);

        public static void Set(string name, object value)
        {
            if (KeyValue.ContainsKey(name))
            {
                KeyValue[name]=value;
            }
            else
            {
                KeyValue.Add(name,value);
            }
        }

        public static T Get<T>(string name, T def = default(T))
        {
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (!KeyValue.ContainsKey(name))
            {
                if (configuration[name] != null)
                {
                    return (T)converter.ConvertFrom(configuration[name]);
                }
              return def;
            }           
            return (T)converter.ConvertFrom(KeyValue[name]);
        }

        public static Dictionary<string, object> GetAll() => KeyValue;

        public static void Set(Dictionary<string,string> keyValuePairs)
        {
            foreach (var item in keyValuePairs)
            {
                Set(item.Key,item.Value);
            }
        }
        public static void Set(Dictionary<string, object> keyValuePairs)
        {
            foreach (var item in keyValuePairs)
            {
                Set(item.Key, item.Value);
            }
        }
    }
}
